/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;

import core.Student;
import db.dao.StudentDAO;
import javax.annotation.PostConstruct;
//import javax.annotation.Resource;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;

/**
 *
 * Validates a users login and also logs out and unvalidates a session.
 * Also navigates from the login view to the secure/main view.
 *
 * @author jonas
 */
public class LoginHandlerBean {
    //@Resource(mappedName="LoginBean", type=beans.LoginBean.class)
    private LoginBean lb;
    private HttpSession https;
    private boolean loggedIn;
    private String toView;

    @PostConstruct
    void init(){
        loggedIn = false;
        toView = "main";
        FacesContext facesCont = FacesContext.getCurrentInstance();
        https = (HttpSession)facesCont.getExternalContext().getSession(false);
        lb = (LoginBean)https.getAttribute(LoginBean.MANGED_BEAN_NAME);
    }

    public void checkLogin(ActionEvent e){
        Student storedUser = StudentDAO.searchForPw(lb.getUname());
        if(storedUser == null){
            lb.setUserLoggedIn(false);
            return;
        }
        loggedIn = storedUser.getPassword().equals(lb.getPw());
        //Set login status in login session bean
        lb.setUserLoggedIn(loggedIn);
        lb.setId(storedUser.getId());
        //Make navigate go to main page if login is succesfull
        toView = "main";
    }

    public void performLogout(ActionEvent e){
        https.invalidate();
        System.out.println("Session invalidated");
        toView = "logout";
    }

    /**
     * Called after data has been submited to deterimine success of fail view
     */
    public Object navigate(){

        if(toView.equals("main")){
            if(!loggedIn){
                System.out.println("loginFail");
                return "loginFail";
            }
            //Loggin successful
            return toView;
        }

        System.out.println("login out");
        //Loggin out
        return toView;
    }
}
